package cn.jksoft.businessclient.ui.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.jksoft.businessclient.R;
import cn.jksoft.businessclient.api.ReceivingService;
import cn.jksoft.businessclient.base.BaseApplication;
import cn.jksoft.businessclient.base.BaseFragment;
import cn.jksoft.businessclient.bean.BaseEntity;
import cn.jksoft.businessclient.bean.OnlineOrderListEntity;
import cn.jksoft.businessclient.bean.OperatePersonEntity;
import cn.jksoft.businessclient.ui.adapter.ConstructionPersonAdapter;
import cn.jksoft.businessclient.ui.adapter.OnlineOrderAdapter;
import cn.jksoft.businessclient.ui.views.RecycleViewDivider;
import cn.jksoft.businessclient.utils.DialogHelp;
import cn.jksoft.businessclient.widgets.RecyclerItemClickListener;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Author:  nick
 * Email:   nickdevp@gmail.com
 * Date:    16/04/07
 * Description:
 */
public class AllOrderFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener{
    @Bind(R.id.swipe_container)
    SwipeRefreshLayout mSwipeLayout;
    @Bind(R.id.recyclerview_onlie_order_list)
    RecyclerView mRecyclerView;

    private LinearLayoutManager linearLayoutManager;
    private StaggeredGridLayoutManager sLayoutManager;
    private int lastVisibleItem;
    private boolean isLoadMore;
    private OnlineOrderAdapter adapter;
    private ConstructionPersonAdapter sAdapter;
    private int pageNo = 1;
    private boolean isNoMore;
    private List<OnlineOrderListEntity.ObjListBean> dataBeanList;
    private ProgressDialog progressDialog,mProgressDialog;
    private Dialog personDialog;
    private String cpName,cpId,cpType;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_online_order, container,
                false);
        ButterKnife.bind(this, view);
        initView();
        return view;
    }
    private void initView(){
        linearLayoutManager = new LinearLayoutManager(getActivity());
        mSwipeLayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL));
        dataBeanList = new ArrayList<OnlineOrderListEntity.ObjListBean>();
        adapter = new OnlineOrderAdapter(getActivity(), dataBeanList);        adapter.setItemClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             //   startActivity(new Intent(getActivity(), CustomerSelectActivity.class));
            }
        });
        adapter.setButtonClickListenner(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                OnlineOrderListEntity.ObjListBean bean = dataBeanList.get((int)(v.getTag()));
                if(bean.getOrderState().equals("10002")) {
                    operOrder(bean.getOrderFlowId()+"");
                }else if(bean.getOrderState().equals("10004")){
                    finishService(bean.getOrderFlowId()+"");
                }
            }
        });
        mRecyclerView.setAdapter(adapter);
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorSchemeResources(R.color.colorPrimary, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, R.color.colorPrimary);
        mSwipeLayout.setDistanceToTriggerSync(400);
        mSwipeLayout.setColorSchemeColors(R.color.white);
        mSwipeLayout.setRefreshing(true);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState ==RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 ==adapter.getItemCount()) {
                    if(!isLoadMore) {
                        if(!isNoMore){
                            getOrderData();
                        }
                    }
                    isLoadMore = true;
                }
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView,dx, dy);
                lastVisibleItem =linearLayoutManager.findLastVisibleItemPosition();
            }
        });
        getOrderData();
    }

    private void getOrderData(){
        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("storeId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getStoreId());
            json.put("orderState","");
            json.put("pageSize", "10");
            json.put("currentPage",pageNo+"");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ReceivingService.createReceivingService().getOnlineOrderList(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OnlineOrderListEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(OnlineOrderListEntity entity) {
                        if (entity.getObjList() != null) {
                            if(pageNo == 1){
                                dataBeanList.clear();
                            }
                            if (entity.getObjList().size() >= 10) {
                                pageNo++;
                            }else{
                                isNoMore = true;
                            }
                            dataBeanList.addAll(entity.getObjList());
                            adapter.notifyDataSetChanged();
                        }else if(pageNo !=1 && entity.getObjList() == null){
                            dataBeanList.clear();
                            adapter.notifyDataSetChanged();
                        }

                        isLoadMore = false;
                        mSwipeLayout.setRefreshing(false);

                    }
                });
    }

    private void operOrder(String orderFlowId){
        progressDialog = DialogHelp.getWaitDialog(getActivity(),"正在确认...");
        progressDialog.show();
        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("partyId",BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getAdminUserId());
            json.put("orderFlowId", orderFlowId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ReceivingService.createReceivingService().operOrder(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.dismiss();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BaseEntity entity) {
                        if("1".equals(entity.getIs_successful())) {
                            showToast("确认成功");
                            mSwipeLayout.setRefreshing(true);
                            pageNo = 1;
                            getOrderData();
                        }else{
                            showToast("确认失败");
                        }
                        progressDialog.dismiss();

                    }
                });
    }


    private void finishService(final String orderFlowId){
        mProgressDialog = DialogHelp.getWaitDialog(getActivity(),"正在确认...");
        mProgressDialog.show();
        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("storeId",BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getStoreId()+"");
            json.put("tenantId", BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getTenantId()+"");
            json.put("currentPage",1);
            json.put("pageSize",100);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ReceivingService.createReceivingService().qryStrucPersonList(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OperatePersonEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mProgressDialog.dismiss();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(OperatePersonEntity entity) {
                        if("1".equals(entity.getIs_successful())) {
                            MyDialog(getActivity(),entity.getPersonnelList(),orderFlowId);
                        }else{
                            showToast("确认失败");
                        }
                        mProgressDialog.dismiss();

                    }
                });
    }


    private void MyDialog(Context context, final List<OperatePersonEntity.PersonnelListEntity> list, final String orderFlowId){
        personDialog = new Dialog(context,R.style.MyDialog);
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View mPopView= inflater.inflate(R.layout.dialog_choose_constructor, null);
        TextView confirmBtn =  (TextView) mPopView.findViewById(R.id.confirm_dialog);
        confirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateOrder(orderFlowId);
                personDialog.dismiss();
            }
        });

        RecyclerView pRecylerView = (RecyclerView) mPopView.findViewById(R.id.person_recyclerview);
        sLayoutManager = new StaggeredGridLayoutManager(4,
                StaggeredGridLayoutManager.VERTICAL);
        pRecylerView.setLayoutManager(sLayoutManager);
        pRecylerView.addOnItemTouchListener(new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        for(OperatePersonEntity.PersonnelListEntity entity : list){
                            entity.setSelect(false);
                        }
                        OperatePersonEntity.PersonnelListEntity personnelListEntity = list.get(position);
                        cpName = personnelListEntity.getCpName();
                        cpId = personnelListEntity.getCpId();
                        cpType = personnelListEntity.getCpType();
                        personnelListEntity.setSelect(true);
                        sAdapter.notifyDataSetChanged();
                    }
                })
        );

        sAdapter = new ConstructionPersonAdapter(context, list);
        pRecylerView.setAdapter(sAdapter);

        personDialog.setContentView(mPopView);
        Window window = personDialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.shopping_car_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = ((Activity) context).getWindowManager().getDefaultDisplay().getHeight();
        // 设置显示位置
        personDialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        personDialog.setCanceledOnTouchOutside(true);
        personDialog.show();
    }

    private void UpdateOrder(String orderFlowId){
        mProgressDialog = DialogHelp.getWaitDialog(getActivity(),"正在完成服务...");
        mProgressDialog.show();
        JSONObject json = null;
        try {
            json = new JSONObject();
            json.put("partyId",BaseApplication.getInstance().getLoginEntity().getPuxsoftLoginDTO().getAdminUserId());
            json.put("orderFlowId", orderFlowId);
            json.put("cpId", cpId);
            json.put("cpName", cpName);
            json.put("cpType", cpType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ReceivingService.createReceivingService().operOrder(json.toString())
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mProgressDialog.dismiss();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(BaseEntity entity) {
                        if("1".equals(entity.getIs_successful())) {
                            showToast("服务已完成");
                            mSwipeLayout.setRefreshing(true);
                            pageNo = 1;
                            getOrderData();
                        }else{
                            showToast("完成服务失败");
                        }
                        mProgressDialog.dismiss();

                    }
                });
    }

    @Override
    public void onRefresh() {
        pageNo = 1;
        getOrderData();
    }
}
